//
//  ZYHomeCouseListController.m
//  优学荟管理系统
//
//  Created by edz on 2017/12/25.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "ZYHomeCouseListController.h"
#import "ZYHomeCouseListCell.h"
#import "ZYHomeCouseListsssModel.h"
#import "ZYJobAnnotationsController.h"
#define kCell @"cell"
#import "ImgZoom.h"
#import <AFNetworking.h>
#import "EMCDDeviceManager.h"
#import "HNHomeCouseListCell.h"
#import "HNAssignmentVC.h"

@interface ZYHomeCouseListController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIWebViewDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) UIView *allView;
@property (nonatomic,assign) BOOL isTrue;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,strong) UIView *allsView;
@property (nonatomic,strong) UITextField *searchTextField;
@property (nonatomic,strong) UIButton *searchButton;

@property (nonatomic,strong) UIWebView *webView;

@end

@implementation ZYHomeCouseListController

- (NSMutableArray *)dataSource{
    
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = ColorRGB(247,245, 245);
    
    [self setSearchName];
    [self setUpSuperView];
    [self setUpRefresh];
    
    
}


- (UIWebView *)webView{
    
    if (_webView == nil) {
        self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(1, 1, 1, 1)];
        self.webView.delegate =self;
        [self.view addSubview:self.webView];
    }
    
    return _webView;
    
    
    
}



- (void)setSearchName{
    
    self.allsView = [[UIView alloc]initWithFrame:CGRectMake(40, 0, kScreenWidth - 80, 30)];
    self.allsView.backgroundColor = ColorRGB(247,245,245);
    self.allsView.layer.cornerRadius = 15;
    self.allsView.clipsToBounds = YES;
    self.navigationItem.titleView = self.allsView;
    
    self.searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, self.allsView.frame.size.width, self.allsView.frame.size.height)];
    self.searchTextField.font = [UIFont systemFontOfSize:13];
    self.searchTextField.textColor = ColorRGB(102, 102, 102);
    self.searchTextField.textAlignment = NSTextAlignmentCenter;
    self.searchTextField.returnKeyType =  UIReturnKeySearch;
    self.searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.searchTextField.delegate = self;
    [self.allsView addSubview:self.searchTextField];
    
    self.searchButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.searchButton setImage:[UIImage imageNamed:@"icon_serch_default"] forState:(UIControlStateNormal)];
    [self.searchButton setTitle:@"  搜索作业" forState:(UIControlStateNormal)];
    [self.searchButton setTitleColor:ColorRGB(102, 102, 102) forState:(UIControlStateNormal)];
    self.searchButton.titleLabel.font = [UIFont systemFontOfSize:13];
    self.searchButton.frame = self.searchTextField.frame;
    [self.allsView addSubview:self.searchButton];
    
    [self.searchButton addTarget:self action:@selector(searchButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.searchTextField addTarget:self action:@selector(searchTextFieldAction:) forControlEvents:(UIControlEventEditingChanged)];
    
    
    
}


- (void)searchButtonAction:(UIButton *)sender{
    
    
    [self.searchTextField becomeFirstResponder];
    
}

- (void)searchTextFieldAction:(UITextField *)textField{
    
    
    self.searchButton.hidden = textField.text.length;
    
    
    
    
}

#pragma mark --- 上拉加载和下拉刷新方法的实现
- (void)setUpRefresh{
    
    //下拉刷新
    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    //自动更改透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    //结束头部刷新
    [self.tableView.mj_header endRefreshing];
    //结束尾部刷新
    [self.tableView.mj_footer endRefreshing];
    
    
}

/**
 *  上拉加载
 */
- (void)upRefresh{
    
    self.isTrue = NO;
    self.page++;
    [self setNetWork];
    
}
/**
 *  下拉刷新
 */

- (void)downRefresh{
    self.isTrue = YES;
    self.page = 1;
    [self setNetWork];
    
    
}






- (void)setNetWork{
    
    //    http://192.168.0.113:8080/StarShine/ys/assignHomework.do?action=getHomeWorkByTea&searchName=&pageNumber=1
    NSString *url = [NSString stringWithFormat:@"assignHomework.do?action=getHomeWorkByTea&searchName=%@&pageNumber=%ld",self.searchTextField.text?self.searchTextField.text:@"",(long)self.page];
    NSString *changeUilStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSLog(@"%@  %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
    
    
    
    [NetManager Get:LLBaseURL(changeUilStr) Auth:YES Params:nil Success:^(id Obj) {
        
        [SVProgressHUD dismiss];
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
            if (self.isTrue == YES) {
                [self.dataSource removeAllObjects];
            }
            NSDictionary *t = [Obj valueForKey:@"t"];
            
            
            NSArray *dataList = [t valueForKey:@"dataList"];
            
            
            for (NSDictionary *dict in dataList) {
                
                ZYHomeCouseListsssModel *model = [ZYHomeCouseListsssModel new];
                model.ID = [dict valueForKey:@"id"];
                model.video = [dict valueForKey:@"video"];
                
                [model setValuesForKeysWithDictionary:dict];
                
                [self.dataSource addObject:model];
                
            }
            
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
        }
        
        
        
        
        
        
    } Fail:^(NSError *Error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        
    }];
    
    
}





- (void)setUpSuperView{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(8,0, kScreenWidth - 16, kScreenHeight - 64)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(-54, 0, 0, 0);
    [self.view addSubview:self.tableView];
    self.tableView.estimatedRowHeight = 150;
    self.tableView.backgroundColor = ColorRGB(247, 245, 245);
    [self.tableView registerNib:[UINib nibWithNibName:[HNHomeCouseListCell description] bundle:nil] forCellReuseIdentifier:@"listCell"];
    [self.tableView registerClass:[ZYHomeCouseListCell class] forCellReuseIdentifier:kCell];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    //self.tableView.estimatedRowHeight = kARHeightTranslator(276);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.allView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight *20/1334)];
    self.allView.backgroundColor = ColorRGB(247, 245, 245);
    self.tableView.tableHeaderView = self.allView;
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    
//    ZYHomeCouseListsssModel *model = [self.dataSource objectAtIndex:indexPath.row];
//    if([model.flag integerValue]!=1&&[model.count integerValue]>0)
//    {
//        
//        
//    }
    
    ZYHomeCouseListsssModel *model = self.dataSource[indexPath.row];
    HNHomeCouseListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listCell" forIndexPath:indexPath];
    cell.model = model;
    // 播放
    cell.ClickImgAction = ^(NSString *urlStr, UIImageView *sender) {
        
        
        
        NSString *Str = [urlStr pathExtension];
        if ([Str isEqualToString:@"png"] || [Str isEqualToString:@"jpg"]) {
            
            UIButton *Button = [UIButton new];
            Button.frame = CGRectMake(0.1, 0.1, 0.1, 0.1);
            [Button setBackgroundImage:sender.image forState:(UIControlStateNormal)];
            [ImgZoom MgrButtonImgView:Button];
            
        } else if ([Str isEqualToString:@"amr"] || [Str isEqualToString:@"mp3"]) {
            
            [self PlayerWithUrlStr:urlStr];
            
            
        } else {
            
            [self.webView loadRequest:[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:model.video]]];
            self.webView.hidden =NO;
        }
        
    };
    
    
    // 长按保存
    cell.ClickImgSaveAction = ^(NSString *urlStr, UIImageView *sender) {
        
        
        
        if ([[urlStr pathExtension] isEqualToString:@"png"] || [[urlStr pathExtension] isEqualToString:@"jpg"]) {
            
            
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"保存图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"取消保存图片");
            }];
            
            UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"确认保存图片");
                
                
                NSURL * url = [NSURL URLWithString:urlStr];
                dispatch_queue_t xrQueue = dispatch_queue_create("loadImage", NULL);
                dispatch_async(xrQueue, ^{
                    UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImageWriteToSavedPhotosAlbum(img,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
                    });
                });
                
                
            }];
            
            [alertControl addAction:cancel];
            [alertControl addAction:confirm];
            
            [self presentViewController:alertControl animated:YES completion:nil];
            
            
        }else if ([[urlStr pathExtension] isEqualToString:@"amr"] || [[urlStr pathExtension] isEqualToString:@"mp3"]){
            
            
        }else{
            
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"保存视频" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
                
                
                [NetManager Down:model.video Auth:YES Params:nil completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                    
                    ALAssetsLibrary *libraty = [ALAssetsLibrary new];
                    
                    [libraty writeVideoAtPathToSavedPhotosAlbum:filePath completionBlock:^(NSURL *assetURL, NSError *error) {
                        
                        if (error) {
                            NSLog(@"错误");
                        }else{
                            NSLog(@"成功");
                        }
                        
                    }];
                    
                }];
                
                
                
                
            }];
            
            [alertControl addAction:cancel];
            [alertControl addAction:confirm];
            
            [self presentViewController:alertControl animated:YES completion:nil];
            
        }
        
        
        
        
        
    };
    
    /// 跳转修改作业
    cell.callBack = ^(NSString *ID) {
        HNAssignmentVC *VC = [HNAssignmentVC new];
        VC.type = HNAssignmentTypeModifying;
        VC.index = indexPath;
        VC.ID = ID;
        //回调刷新 某一行
        VC.ReloadBack = ^(NSIndexPath *index) {
            //删除数据源
            self.isTrue = YES;
            //重新拿数据
            [self setNetWork];
            //延迟一秒 刷新cell
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
            });
            
        };
        [self.navigationController pushViewController:VC animated:YES];
    };
    
    return cell;
    
    
    //    ZYHomeCouseListCell *cell = [tableView dequeueReusableCellWithIdentifier:kCell forIndexPath:indexPath];
    //    ZYHomeCouseListsssModel *model = self.dataSource[indexPath.row];
    //
    //    [cell assignByZYHomeCouseListsssModel:model];
    //
    //    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    //
    //    [cell.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    //    UILongPressGestureRecognizer *longRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longRecognizerAction:)];
    //
    //    [cell.playButton addGestureRecognizer:longRecognizer];
    //
    //
    //
    //
    //    //第一张图片的点击事件
    //    UILongPressGestureRecognizer *longRecognizerTwo = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longRecognizerActionTwo:)];
    //
    //    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    //
    //    cell.photoImageView.userInteractionEnabled = YES;
    //    [cell.photoImageView addGestureRecognizer:longRecognizerTwo];
    //    [cell.photoImageView addGestureRecognizer:tap];
    //
    //
    //
    //
    //
    //    //第二张图片的点击事件
    //    UILongPressGestureRecognizer *longRecognizerThree = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longRecognizerActionThree:)];
    //
    //    UITapGestureRecognizer *tapTow = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapActionTap:)];
    //
    //    cell.photoTwoImageView.userInteractionEnabled = YES;
    //    [cell.photoTwoImageView addGestureRecognizer:longRecognizerThree];
    //    [cell.photoTwoImageView addGestureRecognizer:tapTow];
    //
    //
    //
    //
    //
    //
    //    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    ZYHomeCouseListsssModel *model = [self.dataSource objectAtIndex:indexPath.row];
    ZYJobAnnotationsController *vc = [ZYJobAnnotationsController new];
    vc.ID = [NSString stringWithFormat:@"%@",model.ID];
    [self.navigationController pushViewController:vc animated:YES];
    
    
}


#pragma mark --- 视频播放方法的实现
- (void)playButtonAction:(UIButton *)sender{
    
    
    ZYHomeCouseListCell *cell = (ZYHomeCouseListCell *)sender.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    ZYHomeCouseListsssModel *model = self.dataSource[indexPath.row];
    
    
    [self.webView loadRequest:[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:model.video]]];
    self.webView.hidden =NO;
    
    
    
    
    
}


#pragma mark --- 保存视频方法的实现
- (void)longRecognizerAction:(UILongPressGestureRecognizer *)gesture{
    
    ZYHomeCouseListCell *cell = (ZYHomeCouseListCell *)gesture.view.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    ZYHomeCouseListsssModel *model = self.dataSource[indexPath.row];
    
    
    NSLog(@"%@",model.ID);
    
    
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"保存视频" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        
        
        [NetManager Down:model.video Auth:YES Params:nil completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            
            ALAssetsLibrary *libraty = [ALAssetsLibrary new];
            
            [libraty writeVideoAtPathToSavedPhotosAlbum:filePath completionBlock:^(NSURL *assetURL, NSError *error) {
                
                if (error) {
                    NSLog(@"错误");
                }else{
                    NSLog(@"成功");
                }
                
            }];
            
        }];
        
        
        
        
    }];
    
    [alertControl addAction:cancel];
    [alertControl addAction:confirm];
    
    [self presentViewController:alertControl animated:YES completion:nil];
    
}





#pragma mark --- 第一张图片保存方法的实现
- (void)longRecognizerActionTwo:(UILongPressGestureRecognizer *)gesture{
    
    ZYHomeCouseListCell *cell = (ZYHomeCouseListCell *)gesture.view.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    ZYHomeCouseListsssModel *model = self.dataSource[indexPath.row];
    
    
    
    if ([[model.paths[0] pathExtension] isEqualToString:@"png"] || [[model.paths[0] pathExtension] isEqualToString:@"jpg"]) {
        
        if(gesture.state==UIGestureRecognizerStateBegan){
            
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"保存图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"取消保存图片");
            }];
            
            UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"确认保存图片");
                
                
                NSURL * url = [NSURL URLWithString:model.paths[0]];
                dispatch_queue_t xrQueue = dispatch_queue_create("loadImage", NULL);
                dispatch_async(xrQueue, ^{
                    UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImageWriteToSavedPhotosAlbum(img,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
                    });
                });
                
                
                
                
                
                
                
            }];
            
            [alertControl addAction:cancel];
            [alertControl addAction:confirm];
            
            [self presentViewController:alertControl animated:YES completion:nil];
            
        }
        
    }else if ([[model.paths[0] pathExtension] isEqualToString:@"amr"] || [[model.paths[0] pathExtension] isEqualToString:@"mp3"]){
        
        
    }else{
        
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
}

- (void) savedPhotoImage:(UIImage*)image didFinishSavingWithError: (NSError *)error contextInfo: (void *)contextInfo {
    if (error) {
        NSLog(@"保存视频失败%@", error.localizedDescription);
    }
    else {
        NSLog(@"保存视频成功");
    }
    
}




#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(id)contextInfo

{
    
    NSString*message =@"";
    
    if(!error) {
        
        message =@"成功保存到相册";
        
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertControl addAction:action];
        
        [self presentViewController:alertControl animated:YES completion:nil];
        
    }else
        
    {
        
        message = [error description];
        
        
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertControl addAction:action];
        
        [self presentViewController:alertControl animated:YES completion:nil];
        
    }
    
}



#pragma mark --- 点击第一张图片方法的实现
- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    ZYHomeCouseListCell *cell = (ZYHomeCouseListCell *)tap.view.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    ZYHomeCouseListsssModel *model = self.dataSource[indexPath.row];
    
    
    if ([[model.paths[0] pathExtension] isEqualToString:@"png"] || [[model.paths[0] pathExtension] isEqualToString:@"jpg"]) {
        UIImageView *ImageView = (UIImageView *)tap.view;
        UIButton *Button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        Button.frame = CGRectMake(0, 0, 0.1, 0.1);
        [Button setBackgroundImage:ImageView.image forState:(UIControlStateNormal)];
        [ImgZoom MgrButtonImgView:Button];
        
    }else if ([[model.paths[0] pathExtension] isEqualToString:@"amr"] || [[model.paths[0] pathExtension] isEqualToString:@"mp3"]){
        
        [self PlayerWithUrlStr:model.paths[0]];
    }else{
        
        
    }
    
    
    
    
    
    
    
    
}


#pragma mark ---- 第二张图片保存方法的实现
- (void)longRecognizerActionThree:(UILongPressGestureRecognizer *)gesture{
    
    ZYHomeCouseListCell *cell = (ZYHomeCouseListCell *)gesture.view.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    ZYHomeCouseListsssModel *model = self.dataSource[indexPath.row];
    
    
    
    if ([[model.paths[0] pathExtension] isEqualToString:@"png"] || [[model.paths[0] pathExtension] isEqualToString:@"jpg"]) {
        
        if(gesture.state==UIGestureRecognizerStateBegan){
            
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"保存图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"取消保存图片");
            }];
            
            UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"确认保存图片");
                
                
                NSURL * url = [NSURL URLWithString:model.paths[0]];
                dispatch_queue_t xrQueue = dispatch_queue_create("loadImage", NULL);
                dispatch_async(xrQueue, ^{
                    UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImageWriteToSavedPhotosAlbum(img,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
                    });
                });
                
                
                
                
                
                
                
            }];
            
            [alertControl addAction:cancel];
            [alertControl addAction:confirm];
            
            [self presentViewController:alertControl animated:YES completion:nil];
            
        }
        
    }else if ([[model.paths[0] pathExtension] isEqualToString:@"amr"] || [[model.paths[0] pathExtension] isEqualToString:@"mp3"]){
        
        [self PlayerWithUrlStr:model.paths[0]];
        
    }else{
        
        
    }
    
    
    
    
    
}

#pragma mark --- 第二张图片点击方法的实现
- (void)tapActionTap:(UITapGestureRecognizer *)tap{
    
    ZYHomeCouseListCell *cell = (ZYHomeCouseListCell *)tap.view.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    ZYHomeCouseListsssModel *model = self.dataSource[indexPath.row];
    
    
    if ([[model.paths[1] pathExtension] isEqualToString:@"png"] || [[model.paths[1] pathExtension] isEqualToString:@"jpg"]) {
        UIImageView *ImageView = (UIImageView *)tap.view;
        UIButton *Button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        Button.frame = CGRectMake(0, 0, 0.1, 0.1);
        [Button setBackgroundImage:ImageView.image forState:(UIControlStateNormal)];
        [ImgZoom MgrButtonImgView:Button];
        
    }else if ([[model.paths[1] pathExtension] isEqualToString:@"amr"] || [[model.paths[1] pathExtension] isEqualToString:@"mp3"]){
        
        [self PlayerWithUrlStr:model.paths[1]];
    }else{
        
        
    }
    
    
    
    
    
    
    
    
}









#pragma mark UIWebDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    self.webView =nil;
}




- (void)PlayerWithUrlStr:(NSString *)UrlStr
{
    if ([EMCDDeviceManager sharedInstance].isPlaying) {
        [[EMCDDeviceManager sharedInstance] stopPlaying];
    } else {
        [self RefreshDataForAmr:UrlStr Complete:^(NSString *FullPath) {
            
            FullPath = [FullPath substringFromIndex:7];
            [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:FullPath completion:^(NSError *error) {
                NSLog(@"播放完成");
            }];
        }];
    }
}



- (void)RefreshDataForAmr:(NSString *)UrlStr Complete:(void(^)(NSString *FullPath))Complete
{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AMR"];
    
    
    [NetManager DownLoadFileWithUrlStr:UrlStr FileName:[UrlStr lastPathComponent] Path:path Progress:^(CGFloat Index) {
        
    } Complete:^(NSString *FullPath, NSError *Err) {
        [MBProgressHUD hideHUD];
        if (Err)
        {
            [MBProgressHUD showError:@"音频文件播放失败"];
        }
        else
        {
            Complete (FullPath);
        }
    }];
    
}






































- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.searchTextField resignFirstResponder];
    
    [self.tableView.mj_header beginRefreshing];
    
    return YES;
}







- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [self.searchTextField resignFirstResponder];
    [[EMCDDeviceManager sharedInstance] stopPlaying];
    
    
}

@end

